package com.mystudy.netty.echo.version_1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * @author 周志龙
 * @Email 15216876513@163.com
 * @Date on 2019/10/23 22:08
 * @Description 服务器引导类
 */
public class EchoServer {
    /**
     * logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(EchoServer.class);
    private int port = 0;

    public EchoServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws InterruptedException {
        new EchoServer(10000).start();
    }

    public void start() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        final EchoServerHandler serverHandler = new EchoServerHandler();
        bootstrap.group(group)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(port))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                .addLast(new TestOutboundHandler())
                                .addLast(serverHandler)
                                .addLast(new TestInboundHandler())
                                ;
                    }
                });
        try {
            LOGGER.debug("尝试绑定端口channel");
            ChannelFuture future = bootstrap.bind().sync();
            LOGGER.debug("绑定端口成功");

            Channel channel = future.channel();
            LOGGER.debug("channel = [{}]", channel);

            LOGGER.debug("尝试关闭channel");
            ChannelFuture closeFuture = future.channel().closeFuture();
            LOGGER.debug("closeFuture = [{}]", closeFuture);
            closeFuture.sync();
            LOGGER.debug("关闭channel成功");
        } finally {
            LOGGER.debug("尝试关闭group");
            group.shutdownGracefully().sync();
            LOGGER.debug("关闭group成功");
        }
    }

}
